package io.hepu.robotize.util;

import java.util.Iterator;
import java.util.Map;

public class MapKeyReplacer {

    @FunctionalInterface
    public interface FieldMapper<K> {
        K map(K fieldName);
    }

    public static <K, V> void replace(Map<K, V> map, FieldMapper<K> fieldMapper) {
        Iterator<Map.Entry<K, V>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<K, V> entry = iterator.next();
            K newKey = fieldMapper.map(entry.getKey());
            // Replace only if keys differ
            if (!entry.getKey().equals(newKey)) {
                iterator.remove(); // Prevent ConcurrentModificationException
                map.put(newKey, entry.getValue());
            }
        }
    }
}

